package com.java202411.service.session;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import com.java202411.entity.SessionEntity;
import com.java202411.repository.client.UserDatabaseClient;
import com.java202411.repository.table.UserTable;
import com.java202411.service.commons.NotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@RequiredArgsConstructor
public class SessionService {
    private final UserDatabaseClient userRepository;

    public SessionEntity createSession(String email, String password) {
        Optional<UserTable> user = userRepository.findByEmail(email);

        if (user.isEmpty()) {
            throw new NotFoundException("email 不存在");
        }

        if (user.get().getPassword().equals(password)) {
            String accessToken = JWT.create()
                    .withClaim("email", email)
                    .withExpiresAt(new Date(System.currentTimeMillis() + TimeUnit.MINUTES.toMillis(30)))
                    .sign(Algorithm.HMAC256("this is jwt secret"));

            return SessionEntity.builder()
                    .accessToken(accessToken)
                    .build();
        } else {
            throw new RuntimeException("密码错误");
        }
    }
}
